package com.dfbz.demo04_多态的转型;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo01 {

    public static void main(String[] args) {


//        Animal animal = new Cat();
//        Dog dog = (Dog) animal;         //  java.lang.ClassCastException:类型转换异常


//        Animal animal = new Animal();
//        Dog dog = (Dog) animal;           // java.lang.ClassCastException:类型转换异常

        // 总结: 向下转型的时候,必须要求对象就是源类型

        Animal animal=new Cat();

        if(animal instanceof Cat){

            Cat cat=(Cat) animal;
            cat.eat();
            cat.catchMouse();

        } else if(animal instanceof Dog){
            Dog dog=(Dog) animal;
            dog.eat();
            dog.look();
        }else{

            System.out.println("暂时无法识别是什么类型......");
        }
    }


    public static void test(String[] args) {

        // 父类引用指向子类对象(自动类型提升,向上转型)
        Animal animal = new Dog();

        animal.eat();
//        animal.method();

        // 上下转型: 父类类型转换为子类类型
        Dog dog = (Dog) animal;
        dog.look();
    }
}

class Animal {

    public void eat() {
        System.out.println("动物吃饭.....");
    }
}

class Cat extends Animal {
    @Override
    public void eat() {
        System.out.println("猫吃鱼.....");
    }

    public void catchMouse() {
        System.out.println("猫抓老鼠....");
    }
}

class Dog extends Animal {

    public void eat() {
        System.out.println("狗吃骨头...");
    }

    public void look() {
        System.out.println("看门....");
    }
}
